package com.sky.controller.admin;

import com.sky.Service.EmployeeService;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 员工管理
 */
@Slf4j
@RestController(value = "adminEmployeeController")
@RequestMapping("/admin/employee")
@Api(tags = "员工相关接口")
public class EmployeeController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @ApiOperation("员工登录")
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        //token即为返回回来的字符串
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);


        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 员工退出登录
     *
     * @return
     */
    @ApiOperation("员工退出登录")
    @PostMapping("/logout")
    public Result<String> logout() {
        log.info("员工退出登录，清除当前登录用户信息");
        BaseContext.clearCurrentEmpId();
        return Result.success();
    }

    @ApiOperation("修改员工密码")
    @PutMapping("/editPassword")
    public Result<String> modifyEmployeePassword(@RequestBody PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setEmpId(BaseContext.getCurrentEmpId());
        System.out.println("passwordEditDTO:" + passwordEditDTO);
        //清除缓存
        String key="employee_page_*";
        clearCache(key);
        employeeService.modifyEmployeePassword(passwordEditDTO);
        return Result.success("密码修改成功");
    }

    /**
     * 新增员工信息
     *
     * @param employeeDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增员工信息")
    public Result<String> addEmployee(@RequestBody EmployeeDTO employeeDTO) {
        System.out.println("employeeDTO:" + employeeDTO);
        //清除缓存
        String key="employee_page_*";
        clearCache(key);
        employeeService.addEmployee(employeeDTO);
        return Result.success("新增员工成功");
    }

    /**
     * 分页查询员工信息
     *
     * @param employeePageQueryDTO
     * @return
     */
    @ApiOperation("分页查询员工信息")
    @GetMapping("/page")
    public Result<PageResult> getByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        System.out.println("page:" + employeePageQueryDTO.getPage());
        System.out.println("pageSize:" + employeePageQueryDTO.getPageSize());
        System.out.println("name:" + employeePageQueryDTO.getName());
        //先尝试从缓存中获取数据
        String cacheKey = generateCacheKey(employeePageQueryDTO);
        PageResult cachedResult = (PageResult) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            return Result.success(cachedResult);
        }
        // 如果缓存中没有数据，从数据库查询
        PageResult byPage = employeeService.getByPage(employeePageQueryDTO);
        // 将查询到的结果存入Redis缓存
        redisTemplate.opsForValue().set(cacheKey, byPage);
        return Result.success(byPage);
    }

    /**
     * 更新员工状态
     *
     * @param status
     * @param id
     * @return
     */
    @ApiOperation("更新员工状态")
    @PostMapping("/status/{status}")
    public Result<String> updateEmployeeStatus(@PathVariable Integer status, Long id) {
        System.out.println("status:" + status);
        System.out.println("id:" + id);
        //清除缓存
        String key="employee_page_*";
        clearCache(key);
        employeeService.updateEmployeeStatus(status, id);
        return Result.success("更新员工状态成功");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询员工信息")
    @GetMapping("/{id}")
    public Result<Employee> getEmployeeById(@PathVariable Long id) {
        System.out.println("id:" + id);
        Employee employee = employeeService.getEmployeeById(id);
        return Result.success(employee);
    }

    /**
     * 更新员工信息
     *
     * @param employeeDTO
     * @return
     */
    @ApiOperation("更新员工信息")
    @PutMapping
    public Result<String> updateEmployeeInfo(@RequestBody EmployeeDTO employeeDTO) {
        System.out.println("employeeDTO:" + employeeDTO);
        //清除缓存
        String key="employee_page_*";
        clearCache(key);
        employeeService.updateEmployeeInfo(employeeDTO);
        return Result.success("员工信息修改成功");
    }

    // 生成缓存键的方法，根据查询条件生成唯一的缓存键
    private String generateCacheKey(EmployeePageQueryDTO employeePageQueryDTO) {
        return "employee_page_" + employeePageQueryDTO.getPage() + "_" + employeePageQueryDTO.getPageSize();
    }
    /**
     * 清除缓存
     */
    private void clearCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }


}
